package helloworld.service.administrate;

import helloworld.dao.administrate.RoleDao;
import helloworld.dao.administrate.UserDao;
import helloworld.entity.administrate.Authority;
import helloworld.entity.administrate.Role;
import helloworld.entity.administrate.User;
import helloworld.modules.hibernate.Page;
import helloworld.modules.hibernate.PropertyFilter;

import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Sets;

@Service
@Transactional
public class UserService implements UserDetailsService {
	
	private UserDao userDao;
	private RoleDao roleDao;

	@Autowired
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	@Autowired
	public void setRoleDao(RoleDao roleDao) {
		this.roleDao = roleDao;
	}

	@Transactional(readOnly = true)
	public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, DataAccessException {
		User user = userDao.findUniqueBy("username", userName);
		if (user == null) {
			throw new UsernameNotFoundException("用户" + userName + " 不存在");
		}
		Set<GrantedAuthority> authSet = Sets.newHashSet();
		for (Role role : user.getRoleList()) {
			for (Authority authority : role.getAuthorityList()) {
				authSet.add(new GrantedAuthorityImpl(authority.getName()));
			}
		}
		UserDetails userdetails = new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), true, true, true, true, authSet);
		return userdetails;
	}

	@Transactional(readOnly = true)
	public Page<User> searchUser(final Page<User> page,
			final List<PropertyFilter> filters) {
		return userDao.findPage(page, filters);
	}

	@Transactional(readOnly = true)
	public List<Role> getAllRole() {
		return roleDao.getAll("id", true);
	}

	public User getUser(Long id) {
		return userDao.get(id);
	}

	public Role getRole(Long id) {
		return roleDao.get(id);
	}

	public void saveUser(User entity, List<Long> checkedRoleIds) {
		userDao.save(entity, checkedRoleIds);
	}

	public void saveRole(Role entity) {
		roleDao.save(entity);
	}

	public List<Role> searchRole(List<PropertyFilter> filters) {
		return roleDao.find(filters);
	}
}
